package com.amphiprion.prototype.util;

import java.util.HashMap;

public class BitmapUtil {
	private static HashMap<String, NormalizedBitmap> bitmaps = new HashMap<String, NormalizedBitmap>();
	private static HashMap<String, Integer> countUsages = new HashMap<String, Integer>();
	private static ResolutionOptimizer optimizer;;
	private static boolean isInitialized = false;

	public static void init(int coordWidth, int coordHeight, int deviceWidth,
			int deviceHeight) {
		isInitialized = true;
		optimizer = new ResolutionOptimizer(coordWidth, coordHeight,
				deviceWidth, deviceHeight);
	}

	public static void addOptimization(float ratioCoordLimit, String dir,
			float normalizeScale) {
		optimizer.addOptimization(ratioCoordLimit, dir, normalizeScale);
	}

	public static float getScreenScale() {
		return optimizer.screenScale;
	}

	public static NormalizedBitmap loadBitmap(String uri) {
		NormalizedBitmap b = bitmaps.get(uri);
		if (b == null) {
			b = optimizer.getNormalizedBitmap(uri);
			bitmaps.put(uri, b);
			countUsages.put(uri, 1);
		} else {
			countUsages.put(uri, countUsages.get(uri) + 1);
		}
		return b;
	}

	public static void unloadBitmap(String uri) {
		Integer c = countUsages.get(uri);
		if (c != null) {
			if (c > 1) {
				countUsages.put(uri, c - 1);
			} else {
				countUsages.remove(uri);
				NormalizedBitmap nb = bitmaps.remove(uri);
				nb.bitmap = null;
			}
		}
	}

	public static boolean isInitialized() {
		return isInitialized;
	}
}
